<template>
  <div class="user-manage">
    <div class="page-header">
      <h2>用户管理</h2>
      <el-button type="primary" :icon="Plus" @click="handleAdd">添加用户</el-button>
    </div>
    
    <el-table :data="userList" v-loading="loading" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" width="150" />
      <el-table-column prop="nickname" label="昵称" width="150" />
      <el-table-column prop="enable" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.enable ? 'success' : 'info'">
            {{ row.enable ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="isAdmin" label="管理员" width="100">
        <template #default="{ row }">
          <el-tag v-if="row.isAdmin" type="warning">是</el-tag>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" fixed="right">
        <template #default="{ row }">
          <el-button type="text" :icon="Edit" @click="handleEdit(row)">编辑</el-button>
          <el-button 
            type="text" 
            :icon="row.enable ? 'VideoPause' : 'VideoPlay'"
            @click="handleToggleEnable(row)"
          >
            {{ row.enable ? '禁用' : '启用' }}
          </el-button>
          <el-button type="text" :icon="Delete" style="color: #f56c6c" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 添加/编辑用户对话框 -->
    <el-dialog v-model="showUserDialog" :title="isEditUser ? '编辑用户' : '添加用户'" width="500px">
      <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="isEditUser" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="密码" :prop="isEditUser ? '' : 'password'">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="是否管理员">
          <el-switch v-model="userForm.isAdmin" />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch v-model="userForm.enable" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showUserDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitUser">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { adminApi } from '@/api'

const userList = ref([])
const loading = ref(false)
const showUserDialog = ref(false)
const isEditUser = ref(false)
const userFormRef = ref(null)

const userForm = reactive({
  id: null,
  username: '',
  nickname: '',
  password: '',
  isAdmin: false,
  enable: true
})

const userRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

onMounted(async () => {
  await loadUserList()
})

const loadUserList = async () => {
  loading.value = true
  try {
    const res = await adminApi.getUserList()
    userList.value = res.data || []
  } catch (error) {
    ElMessage.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  isEditUser.value = false
  Object.assign(userForm, {
    id: null,
    username: '',
    nickname: '',
    password: '',
    isAdmin: false,
    enable: true
  })
  showUserDialog.value = true
}

const handleEdit = (row) => {
  isEditUser.value = true
  Object.assign(userForm, {
    id: row.id,
    username: row.username,
    nickname: row.nickname,
    password: '',
    isAdmin: row.isAdmin,
    enable: row.enable
  })
  showUserDialog.value = true
}

const handleSubmitUser = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    // 编辑时密码可以为空
    if (isEditUser.value && !userForm.password) {
      delete userForm.password
    }
    
    try {
      await adminApi.saveOrUpdateUser(userForm)
      ElMessage.success(isEditUser.value ? '更新成功' : '添加成功')
      showUserDialog.value = false
      await loadUserList()
    } catch (error) {
      ElMessage.error('保存失败')
    }
  })
}

const handleToggleEnable = async (row) => {
  try {
    if (row.enable) {
      await adminApi.disableUser(row.id)
      ElMessage.success('已禁用')
    } else {
      await adminApi.enableUser(row.id)
      ElMessage.success('已启用')
    }
    await loadUserList()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除用户 "${row.username}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await adminApi.deleteUser(row.id)
    ElMessage.success('删除成功')
    await loadUserList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}
</script>

<style lang="scss" scoped>
.user-manage {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 500;
    }
  }
}
</style>

